import requests


def getUrl(*address):
    ak = 'yHzBf21IrXFkPgMIwyLKipzpKw4nFevc'  # 填入你的api key
    if len(address) < 1:
        return None
    else:
        for add in address:
            url = 'http://api.map.baidu.com/geocoding/v3/?address={0}&output=json&ak={1}'.format(
                add, ak)
            yield url


def getPosition(url):
    '''返回经纬度信息'''
    res = requests.get(url)
    print(res.text)
    json_data = eval(res.text)

    if json_data['status'] == 0:
        lat = json_data['result']['location']['lat']  # 纬度
        lng = json_data['result']['location']['lng']  # 经度
    else:
        print("Error output!")
        return json_data['status']
    return lat, lng


if __name__ == "__main__":
    address = ['北京市清华大学', '北京市北京大学', '保定市华北电力大学', '上海市复旦大学', '武汉市武汉大学']
    for add in address:
        add_url = list(getUrl(add))[0]
        print('url:', add_url)
        try:
            lat, lng = getPosition(add_url)
            print("{0}|经度:{1}|纬度:{2}.".format(add, lng, lat))
        except Exception as e:
            print(e)
